#****************************************************************************************************
# File Start!
#***************************************************************************************************/

#*
 #
 #  Copyright (c) 2024-2025 by flechazo. All rights reserved.
 #
 # Author : CarlChai LinFeng Chai flechazo
 # Website: flechazo.mba
 #
 # Change Logs:
 # Date           Author       Notes
 # 2025-06-14     cc          the first version
 #
#/

#****************************************************************************************************
# Include
#***************************************************************************************************/

import os
import keyboard
import json
from command.command_cfg import command_cfg_execute_action

#****************************************************************************************************
# Define
#***************************************************************************************************/

COPYRIGHT_INFO = \
"""

/*
 *
 *  Copyright (c) 2024-2025 by flechazo. All rights reserved.
 *
 * Author : CarlChai LinFeng Chai flechazo
 * Website: flechazo.mba
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-06-14     cc          the first version
 *
*/

"""

#****************************************************************************************************
# Type Define
#***************************************************************************************************/

#****************************************************************************************************
# Global Variable
#***************************************************************************************************/

# config file #
COMMAND_CONFIG_FILE = "database/shortcut.json"
# global shortcut table #
COMMAND_TABLE = [
    # { "keys" : "", "actions" : "" ,"status" : "unregister"},
]
# read table #
COMMAND_TABLE_INPUT = []

#****************************************************************************************************
# Function Impletement
#***************************************************************************************************/

#****************************************************************************************************
# command_init()
#***************************************************************************************************/
def command_init():
    # load database #
    command_load()
    # register #
    command_register()
    return True

#****************************************************************************************************
# command_table_get()
#***************************************************************************************************/
def command_table_get():
    return COMMAND_TABLE

#****************************************************************************************************
# command_register()
#***************************************************************************************************/
def command_register():
    for command in COMMAND_TABLE_INPUT:
        command["status"] = "unregister"
        command_add(command["keys"],command["actions"])
    return

#****************************************************************************************************
# command_execute_action()
#***************************************************************************************************/
def command_execute_action(action):
    command_cfg_execute_action(action)
    return

#****************************************************************************************************
# command_save()
#***************************************************************************************************/
def command_load():
    global COMMAND_TABLE_INPUT
    # load config #
    if not os.path.exists(COMMAND_CONFIG_FILE):
        return
    # read #
    try:
        with open(COMMAND_CONFIG_FILE, 'r', encoding='utf-8') as f:
            content = f.read()
            # skip copyright info
            json_start = content.find('[')
            if json_start == -1:
                return
            json_content = content[json_start:]
            COMMAND_TABLE_INPUT = json.loads(json_content)
    except json.JSONDecodeError:
        return

#****************************************************************************************************
# command_save()
#***************************************************************************************************/
def command_save():
    with open(COMMAND_CONFIG_FILE, 'w', encoding='utf-8') as f:
        # f.write(COPYRIGHT_INFO) #
        json.dump(COMMAND_TABLE, f, ensure_ascii=False, indent=4)

#****************************************************************************************************
# command_add()
#***************************************************************************************************/
def command_add(key,action):
    # check #
    if any(((item['keys'] == key) and (item['status'] == "register")) for item in COMMAND_TABLE):
        return False
    # add #
    try:
        # shortcut add #
        keyboard.add_hotkey(key, lambda: command_execute_action(action))
        COMMAND_TABLE.append({"keys":key,"actions":action,"status":"register"})
        # save #
        command_save()
        return True
    except Exception:
        return False

#****************************************************************************************************
# command_del()
#***************************************************************************************************/
def command_del(key,action):
    # find #
    for i, item in enumerate(COMMAND_TABLE):
        if (item.get('keys') == key) and (item.get('actions') == action):
            # remove shortcut #
            try:
                keyboard.remove_hotkey(key)
            except KeyError:
                pass
            del COMMAND_TABLE[i]
            # save #
            command_save()
            break

#****************************************************************************************************
# command_re_register()
#***************************************************************************************************/
def command_re_register():
    # re-register all hotkeys #
    for command in COMMAND_TABLE:
        if command["status"] == "register":
            try:
                keyboard.remove_hotkey(command["keys"])
            except KeyError:
                pass
            keyboard.add_hotkey(command["keys"], lambda: command_execute_action(command["actions"]))
    return

#****************************************************************************************************
# exports
#***************************************************************************************************/

#****************************************************************************************************
# File End!
#***************************************************************************************************/
